/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#import <UIKit/UIKit.h>

#import "common.h"
#import "MainView.h"
#import "AccountView.h"
#import "SettingsView.h"
#import "base/Log.h"
#import "UIController.h"
#import "FunambolAPI.h"
#include <time.h>
#include "TimeUtils.h"
#import "customs.h"

#define buttonWidht             314.0f
#define buttonEight             74.0f
#define iconOffSet_x            20.0f
#define textOffSet_x            80.0f
#define funLogoOffSet_y         30.0f
#define contactLogoOffSet_y     122.5f
#define calendarLogoOffSet_y    197.5f
#define taskLogoOffSet_y        270.0f
#define notesLogoOffSet_y        270.0f
//#define notesLogoOffSet_y       342.5f

@implementation MainView

- (id)init {
    
    //struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	UIScreen* ms = [UIScreen mainScreen];
    struct CGRect rect = ms.applicationFrame;
    rect.origin.x = rect.origin.y = 0.0f;
 
    stopDisplayed = false;
    syncContactText = nil;
    syncCalendarText = nil;
    syncNoteText = nil;

    rightTitle = nil;
    self = [super init];
	if (self)
	{
		// this title will appear in the navigation bar
		self.title = NSLocalizedString(@"AppName",@"Funambol");
		
		menuList = [[NSMutableArray alloc] init];
	}
    

	return self;
}

- (void) loadView{
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	self.view = contentView;
	[contentView release];
    
    SettingsView* settingsview = [[SettingsView alloc]init];
    [menuList addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Settings", @""), @"title",
                         settingsview, @"viewController",
                         nil]];
    [settingsview release];
    
    NSString* URL;
    NSString* username;
    NSString* password; 
    
    [[FunambolAPI getInstance] loadSyncConfig:&URL username:&username password:&password];
    
    if([username isEqualToString:@""] || [password isEqualToString:@""]){
        AccountView* accountview = [[AccountView alloc]init];
        [[self navigationController] pushViewController:accountview animated:NO];
        
    }
    StringBuffer urlstring([URL UTF8String]);
    if((urlstring.find(" ") != StringBuffer::npos)||
       (urlstring.find("<") != StringBuffer::npos)||
       (urlstring.find(">") != StringBuffer::npos)){
        AccountView* accountview = [[AccountView alloc]init];
        [[self navigationController] pushViewController:accountview animated:NO];
    } 
    
    [URL      release];
    [username release];
    [password release];
	
	self.view.autoresizesSubviews = YES;
    [self addComponents];
    

        
}

- (void) viewDidAppear:(BOOL)animated{
    NSString* URL;
    NSString* username;
    NSString* password; 
    
    [[FunambolAPI getInstance] loadSyncConfig:&URL username:&username password:&password];
    
    if([username isEqualToString:@""] || [password isEqualToString:@""]){
        AccountView* accountview = [[AccountView alloc]init];
        [[self navigationController] pushViewController:accountview animated:YES];

    }
    StringBuffer urlstring([URL UTF8String]);
    if((urlstring.find(" ") != StringBuffer::npos)||
       (urlstring.find("<") != StringBuffer::npos)||
       (urlstring.find(">") != StringBuffer::npos)){
        AccountView* accountview = [[AccountView alloc]init];
        [[self navigationController] pushViewController:accountview animated:YES];
    } 
    
    [URL      release];
    [username release];
    [password release];

    if([[[FunambolAPI getInstance] getSync:@"addressbook"] isEqualToString:@"none"]){
        [iconContacts setImage:[UIImage imageNamed: @"icon_contacts_g.png"]];
    }else{
        [iconContacts setImage:[UIImage imageNamed: @"icon_contacts.png"]];
    }
    if([[[FunambolAPI getInstance] getSync:@"calendar"] isEqualToString:@"none"]){
        [iconCalendar setImage:[UIImage imageNamed: @"icon_calendar_g.png"]];
    }else{
        [iconCalendar setImage:[UIImage imageNamed: @"icon_calendar.png"]];
    }
    if([[[FunambolAPI getInstance] getSync:@"note"] isEqualToString:@"none"]){
        [iconNotes setImage:[UIImage imageNamed: @"icon_notes_g.png"]];
    }else{
        [iconNotes setImage:[UIImage imageNamed: @"icon_notes.png"]];
    }
    if([[[FunambolAPI getInstance] getSync:@"addressbook"] isEqualToString:@"none"]){
        contactsText.textColor = [UIColor grayColor];
    }else{
        contactsText.textColor = [UIColor blackColor];
    }
    
    if([[[FunambolAPI getInstance] getSync:@"addressbook"] isEqualToString:@"none"]){
        contactsStatusText.textColor = [UIColor grayColor];
    }else{
        contactsStatusText.textColor = [UIColor blackColor];
    }
    
	if([[[FunambolAPI getInstance] getSync:@"calendar"] isEqualToString:@"none"]){
        calendarText.textColor = [UIColor grayColor];
    }else{
        calendarText.textColor = [UIColor blackColor];
    }
    
	if([[[FunambolAPI getInstance] getSync:@"calendar"] isEqualToString:@"none"]){
        calendarStatusText.textColor = [UIColor grayColor];
    }else {
        calendarStatusText.textColor = [UIColor blackColor];
    }
    
    if([[[FunambolAPI getInstance] getSync:@"note"] isEqualToString:@"none"]){
        notesText.textColor = [UIColor grayColor];
    }else {
        notesText.textColor = [UIColor blackColor];
    }
    
    if([[[FunambolAPI getInstance] getSync:@"note"] isEqualToString:@"none"]){
        notesStatusText.textColor = [UIColor grayColor];
    }else {
        notesStatusText.textColor = [UIColor blackColor];
    }
}

- (void) reload {
    [self addComponents];
}

- (void)addComponents {
	
	large_font = [UIFont boldSystemFontOfSize:22];
	small_font = [UIFont systemFontOfSize:13];

    //Setup the screen background
    background = [[UIImageView alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 420.0f)];
    [background setImage:[UIImage imageNamed: @"background.png"]];
    [self.view addSubview:background];

    // The small Funambol logo in the Sync All rectangle
    iconLogo = [[UIImageView alloc] initWithFrame: CGRectMake(iconOffSet_x, funLogoOffSet_y -2.0f , 50.0f, 50.0f)];  
    [iconLogo setImage:[UIImage imageNamed: @"icon_logo.png"]];
    [self.view addSubview:iconLogo];

    // The contacts icon
    iconContacts = [[UIImageView alloc] initWithFrame: CGRectMake(iconOffSet_x, contactLogoOffSet_y , 50.0f, 50.0f)];  
    if([[[FunambolAPI getInstance] getSync:@"addressbook"] isEqualToString:@"none"]){
        [iconContacts setImage:[UIImage imageNamed: @"icon_contacts_g.png"]];
    }else{
        [iconContacts setImage:[UIImage imageNamed: @"icon_contacts.png"]];
    }
        
    [self.view addSubview:iconContacts];
    
    if (!CUSTOM_HIDE_DISABLED_CATEGORIES) { //BEGIN CUSTOM 
     
    // The calendar icon 
    iconCalendar = [[UIImageView alloc] initWithFrame: CGRectMake(iconOffSet_x, calendarLogoOffSet_y , 50.0f, 50.0f)];  
    if([[[FunambolAPI getInstance] getSync:@"calendar"] isEqualToString:@"none"]){
        [iconCalendar setImage:[UIImage imageNamed: @"icon_calendar_g.png"]];
    }else{
        [iconCalendar setImage:[UIImage imageNamed: @"icon_calendar.png"]];
    }
    [self.view addSubview:iconCalendar];
      
    // The tasks icon
    //iconTasks = [[UIImageView alloc] initWithFrame: CGRectMake(iconOffSet_x, taskLogoOffSet_y , 50.0f, 50.0f)];  
    //[iconTasks setImage:[UIImage imageNamed: @"icon_tasks_g.png"]];
    //[self.view addSubview:iconTasks];

    // The notes icon  
    iconNotes = [[UIImageView alloc] initWithFrame: CGRectMake(iconOffSet_x, notesLogoOffSet_y , 50.0f, 50.0f)];
    if([[[FunambolAPI getInstance] getSync:@"note"] isEqualToString:@"none"]){
        [iconNotes setImage:[UIImage imageNamed: @"icon_notes_g.png"]];
    }else{
        [iconNotes setImage:[UIImage imageNamed: @"icon_notes.png"]];
    }
    [self.view addSubview:iconNotes];
    
    } //END CUSTOM

    // The "Sync All" label  
    allText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, funLogoOffSet_y-2.0f, 155.0f, 50.0f)];
    //[allText setBackgroundColor: CGColorCreate(colorSpace, transparent)];
    
    // The "Synchronization" and "To Cancel" Text
    synchronizeText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, funLogoOffSet_y-10.0f, 255.0f, 50.0f)];
    synchronizeText.textColor = [UIColor whiteColor]; 
	synchronizeText.backgroundColor = [UIColor clearColor];
    [synchronizeText setFont: large_font];
    [synchronizeText setText:NSLocalizedString(@"Sync in progress", @"Sync in progress")];  
    
    syncCancelText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, funLogoOffSet_y+10.0f, 255.0f, 50.0f)];
    syncCancelText.textColor = [UIColor whiteColor]; 
	syncCancelText.backgroundColor = [UIColor clearColor];
    [syncCancelText setFont: small_font];
    [syncCancelText setText:NSLocalizedString(@"CancelSyncText", @"CancelSyncText")];  
    

    //[allText setColor: CGColorCreate(colorSpace, white)];
	allText.textColor = [UIColor whiteColor]; 
	allText.backgroundColor = [UIColor clearColor];
    [allText setFont: large_font];
    [allText setText:NSLocalizedString(@"Sync All", @"Sync All")];  
    [self.view addSubview:allText];
	syncButton = [[UIButton alloc]initWithFrame:CGRectMake(2.0f, 10.0f, 315.0f, 80.0f)];
	//[syncButton setButtonType:UIButtonTypeRoundedRect];
	[syncButton setBackgroundColor:[UIColor clearColor]];
	[syncButton addTarget: self action:@selector(syncAllAction:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:syncButton];

	contactsButton = [[UIButton alloc]initWithFrame:CGRectMake(3.0f, 105.0f, 315.0f, 80.0f)];
	[contactsButton setBackgroundColor:[UIColor clearColor]];
	[contactsButton addTarget: self action:@selector(syncContactsAction:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:contactsButton];

    // The "Contacts" label   
    contactsText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, (contactLogoOffSet_y - 10.0f), 150.0f, 50.0f)];
	if([[[FunambolAPI getInstance] getSync:@"addressbook"] isEqualToString:@"none"]){
            contactsText.textColor = [UIColor grayColor];
    }else{
        contactsText.textColor = [UIColor blackColor];
    }
	contactsText.backgroundColor = [UIColor clearColor];
    [contactsText setFont: large_font];
    [contactsText setText: NSLocalizedString(@"Contacts", @"Contacts")];
    [self.view addSubview:contactsText];

    // The status text for Contacts, with the last sync date
    NSString *contactsStatusTextValue = [self getLastSyncMessage:@"addressbook"];
    contactsStatusText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, (contactLogoOffSet_y + 10.0f), 205.0f, 50.0f)];
	
    if([[[FunambolAPI getInstance] getSync:@"addressbook"] isEqualToString:@"none"]){
            contactsStatusText.textColor = [UIColor grayColor];
    }else{
        contactsStatusText.textColor = [UIColor blackColor];
    }
	contactsStatusText.backgroundColor = [UIColor clearColor];
    [contactsStatusText setFont: small_font];
    [contactsStatusText setText:contactsStatusTextValue];  
    [self.view addSubview:contactsStatusText];
     
    if (!CUSTOM_HIDE_DISABLED_CATEGORIES) { //BEGIN CUSTOM 
        
        // The Calendar label
        calendarText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, (calendarLogoOffSet_y - 10.0f), 150.0f, 50.0f)];
        if([[[FunambolAPI getInstance] getSync:@"calendar"] isEqualToString:@"none"]){
            calendarText.textColor = [UIColor grayColor];
        }else{
            calendarText.textColor = [UIColor blackColor];
        }
        calendarText.backgroundColor = [UIColor clearColor];
        [calendarText setFont: large_font];
        [calendarText setText:NSLocalizedString(@"Calendar", @"Calendar")];  
        [self.view addSubview:calendarText];
        
        // The status text for Calendar
        NSString *calendarStatusTextValue = [self getLastSyncMessage:@"calendar"];
        calendarStatusText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, (calendarLogoOffSet_y + 10.0f), 205.0f, 50.0f)];
        if([[[FunambolAPI getInstance] getSync:@"calendar"] isEqualToString:@"none"]){
            calendarStatusText.textColor = [UIColor grayColor];
        }else {
            calendarStatusText.textColor = [UIColor blackColor];
        }
        
        calendarStatusText.backgroundColor = [UIColor clearColor];
        [calendarStatusText setFont: small_font];
        [calendarStatusText setText: calendarStatusTextValue];  
        [self.view addSubview:calendarStatusText];  
     
        calendarButton = [[UIButton alloc]initWithFrame:CGRectMake(3.0f, 185.0f, 315.0f, 80.0f)];
        [calendarButton setBackgroundColor:[UIColor clearColor]];
        [calendarButton addTarget: self action:@selector(syncCalendarAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:calendarButton];
     
        // The Notes label
        notesText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, (notesLogoOffSet_y - 10.0f), 150.0f, 50.0f)];
        if([[[FunambolAPI getInstance] getSync:@"note"] isEqualToString:@"none"]){
            notesText.textColor = [UIColor grayColor];
        }else {
            notesText.textColor = [UIColor blackColor];
        }

        notesText.backgroundColor = [UIColor clearColor];
        [notesText setFont: large_font];
        [notesText setText:NSLocalizedString(@"Notes",@"Notes")];  
        [self.view addSubview:notesText];

        // The status text for Notes 
        NSString *notesStatusTextValue = [self getLastSyncMessage:@"note"];
        notesStatusText = [[UILabel alloc] initWithFrame: CGRectMake(textOffSet_x, (notesLogoOffSet_y + 10.0f), 205.0f, 50.0f)];
        if([[[FunambolAPI getInstance] getSync:@"note"] isEqualToString:@"none"]){
            notesStatusText.textColor = [UIColor grayColor];
        }else {
            notesStatusText.textColor = [UIColor blackColor];
        }

        notesStatusText.backgroundColor = [UIColor clearColor];
        [notesStatusText setFont: small_font];
        [notesStatusText setText:notesStatusTextValue];  
        [self.view addSubview:notesStatusText];  
        notesButton = [[UIButton alloc]initWithFrame:CGRectMake(3.0f, 265.0f, 315.0f, 80.0f)];
        [notesButton setBackgroundColor:[UIColor clearColor]];
        [notesButton addTarget: self action:@selector(syncNoteAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:notesButton];

    } //END CUSTOM 

    // In this section we have views that are not always displayed, but only
    // when needed

    // The sync blue arrows visualized when clicking on Sync All
    iconSyncAllBlue = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, funLogoOffSet_y, 50.0f, 50.0f)];  
    [iconSyncAllBlue setImage:[UIImage imageNamed: @"icon_sync_all_blue.png"]];

    ///////////////////////////////////CONTACTS
    // The #1 white arrow, for the animation of the Contacts sync
    iconContactSyncDark[0] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, contactLogoOffSet_y, 50.0f, 50.0f)];  
    [iconContactSyncDark[0] setImage:[UIImage imageNamed: @"icon_sync1_dark.png"]];
    // The #2 white arrow, for the animation of the Contacts sync
    iconContactSyncDark[1] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, contactLogoOffSet_y, 50.0f, 50.0f)];  
    [iconContactSyncDark[1] setImage:[UIImage imageNamed: @"icon_sync2_dark.png"]];
    // The #3 white arrow, for the animation of the Contacts sync
    iconContactSyncDark[2] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, contactLogoOffSet_y, 50.0f, 50.0f)];  
    [iconContactSyncDark[2] setImage:[UIImage imageNamed: @"icon_sync3_dark.png"]];
    // The #4 white arrow, for the animation of the Contacts sync
    iconContactSyncDark[3] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, contactLogoOffSet_y, 50.0f, 50.0f)];  
    [iconContactSyncDark[3] setImage:[UIImage imageNamed: @"icon_sync4_dark.png"]];
    // The check icon, visualized when Contacts sync is successful
    int idx = MAIN_VIEW_STATUS_ICON_SUCCESS;
    statusContactIcons[idx] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, contactLogoOffSet_y-4.0f, 50.0f, 50.0f)];  
    [statusContactIcons[idx] setImage:[UIImage imageNamed: @"icon_complete.png"]];
    // The alert icon, visualized when Contacts sync failed
    idx = MAIN_VIEW_STATUS_ICON_FAILURE;
    statusContactIcons[idx] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, contactLogoOffSet_y, 50.0f, 50.0f)];  
    [statusContactIcons[idx] setImage:[UIImage imageNamed: @"icon_alert.png"]];

    ///////////////////////////////////CALENDAR
    // The #1 white arrow, for the animation of the Calendar sync
    iconCalendarSyncDark[0] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, calendarLogoOffSet_y, 50.0f, 50.0f)];  
    [iconCalendarSyncDark[0] setImage:[UIImage imageNamed: @"icon_sync1_dark.png"]];
    // The #2 white arrow, for the animation of the Contacts sync
    iconCalendarSyncDark[1] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, calendarLogoOffSet_y, 50.0f, 50.0f)];  
    [iconCalendarSyncDark[1] setImage:[UIImage imageNamed: @"icon_sync2_dark.png"]];
    // The #3 white arrow, for the animation of the Contacts sync
    iconCalendarSyncDark[2] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, calendarLogoOffSet_y, 50.0f, 50.0f)];  
    [iconCalendarSyncDark[2] setImage:[UIImage imageNamed: @"icon_sync3_dark.png"]];
    // The #4 white arrow, for the animation of the Contacts sync
    iconCalendarSyncDark[3] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, calendarLogoOffSet_y, 50.0f, 50.0f)];  
    [iconCalendarSyncDark[3] setImage:[UIImage imageNamed: @"icon_sync4_dark.png"]];
    // The check icon, visualized when Contacts sync is successful
    idx = MAIN_VIEW_STATUS_ICON_SUCCESS;
    statusCalendarIcons[idx] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, calendarLogoOffSet_y-4.0f, 50.0f, 50.0f)];  
    [statusCalendarIcons[idx] setImage:[UIImage imageNamed: @"icon_complete.png"]];
    // The alert icon, visualized when Contacts sync failed
    idx = MAIN_VIEW_STATUS_ICON_FAILURE;
    statusCalendarIcons[idx] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, calendarLogoOffSet_y, 50.0f, 50.0f)];  
    [statusCalendarIcons[idx] setImage:[UIImage imageNamed: @"icon_alert.png"]];
    
    ///////////////////////////////////NOTE
    // The #1 white arrow, for the animation of the Calendar sync
    iconNoteSyncDark[0] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, notesLogoOffSet_y, 50.0f, 50.0f)];  
    [iconNoteSyncDark[0] setImage:[UIImage imageNamed: @"icon_sync1_dark.png"]];
    // The #2 white arrow, for the animation of the Contacts sync
    iconNoteSyncDark[1] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, notesLogoOffSet_y, 50.0f, 50.0f)];  
    [iconNoteSyncDark[1] setImage:[UIImage imageNamed: @"icon_sync2_dark.png"]];
    // The #3 white arrow, for the animation of the Contacts sync
    iconNoteSyncDark[2] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, notesLogoOffSet_y, 50.0f, 50.0f)];  
    [iconNoteSyncDark[2] setImage:[UIImage imageNamed: @"icon_sync3_dark.png"]];
    // The #4 white arrow, for the animation of the Contacts sync
    iconNoteSyncDark[3] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, notesLogoOffSet_y, 50.0f, 50.0f)];  
    [iconNoteSyncDark[3] setImage:[UIImage imageNamed: @"icon_sync4_dark.png"]];
    // The check icon, visualized when Contacts sync is successful
    idx = MAIN_VIEW_STATUS_ICON_SUCCESS;
    statusNoteIcons[idx] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, notesLogoOffSet_y-4.0f, 50.0f, 50.0f)];  
    [statusNoteIcons[idx] setImage:[UIImage imageNamed: @"icon_complete.png"]];
    // The alert icon, visualized when Contacts sync failed
    idx = MAIN_VIEW_STATUS_ICON_FAILURE;
    statusNoteIcons[idx] = [[UIImageView alloc] initWithFrame: CGRectMake(260.0f, notesLogoOffSet_y, 50.0f, 50.0f)];  
    [statusNoteIcons[idx] setImage:[UIImage imageNamed: @"icon_alert.png"]];
    
    
    
    //The dark blue rectangle, visualized when clicking on Sync All  
    buttonDarkBlue = [[UIImageView alloc] initWithFrame: CGRectMake(3.0f, 13.0f, 315.0f, 75.0f)];  
    [buttonDarkBlue setImage:[UIImage imageNamed: @"bg_button_darkblue.png"]];

    // The light blue rectangle, visualized when clicking on Contacts
    contactButtonBlue = [[UIImageView alloc] initWithFrame: CGRectMake(3.0f, 106.0f, 315.0f, 75.0f)];  
    [contactButtonBlue setImage:[UIImage imageNamed: @"bg_button_blue.png"]];
    calendarButtonBlue = [[UIImageView alloc] initWithFrame: CGRectMake(3.0f, 180.0f, 315.0f, 75.0f)];  
    [calendarButtonBlue setImage:[UIImage imageNamed: @"bg_button_blue.png"]];
    noteButtonBlue = [[UIImageView alloc] initWithFrame: CGRectMake(3.0f, 253.0f, 315.0f, 75.0f)];  
    [noteButtonBlue setImage:[UIImage imageNamed: @"bg_button_blue.png"]];


	settingsButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Settings",@"Settings")
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(settingsAction:)];

    self.navigationItem.rightBarButtonItem = settingsButton;
    

}


- (void)disableAllButtons {
    // TODO we should disable the sync buttons as well
	[syncButton removeFromSuperview];
	[contactsButton removeFromSuperview];
    [calendarButton removeFromSuperview];
    [notesButton removeFromSuperview];
    self.navigationItem.rightBarButtonItem = nil;
    
}

- (void)enableAllButtons {
	[self.view addSubview:syncButton];
	[self.view addSubview:contactsButton];
    [self.view addSubview:calendarButton];
    [self.view addSubview:notesButton];
    settingsButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Settings",@"Settings")
                                                      style:UIBarButtonItemStylePlain
                                                     target:self
                                                     action:@selector(settingsAction:)];
    
    self.navigationItem.rightBarButtonItem = settingsButton;

}

- (void)syncAllAction: (id)sender{
	[[UIController getInstance] syncAll];
}
- (void)syncContactsAction: (id)sender{
    if([[[FunambolAPI getInstance] getSync:@"addressbook"] isEqualToString:@"none"]){
        //just don't do anything
    }else{
        [[UIController getInstance] sync:@"addressbook"];
    }
}

- (void)syncCalendarAction: (id)sender{
    if([[[FunambolAPI getInstance] getSync:@"calendar"] isEqualToString:@"none"]){
        //just don't do anything
    }else{
        [[UIController getInstance] sync:@"calendar"];
    }
}

- (void)syncNoteAction: (id)sender{
    if([[[FunambolAPI getInstance] getSync:@"note"] isEqualToString:@"none"]){
        //just don't do anything
    }else{
        [[UIController getInstance] sync:@"note"];
    }
}

- (void)settingsAction:(id)sender
{

	UIViewController *targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
	[[self navigationController] pushViewController:targetViewController animated:YES];
}

- (void)stopAction:(id)sender
{
    [[UIController getInstance] stopSyncContacts];
}

- (void) setStartSyncAnimation:(NSString*) sourcename start:(bool) start{
    if([sourcename isEqualToString:@"addressbook"]){
        contactSyncAnimation = start;
    }else if([sourcename isEqualToString:@"calendar"]){
        calendarSyncAnimation = start;
    }else if([sourcename isEqualToString:@"note"]){
        noteSyncAnimation = start;
    }
}
    

- (void) setFinalMsg:(NSString*) sourcename result: (int) result{
    if([sourcename isEqualToString:@"addressbook"]){
    }else if([sourcename isEqualToString:@"calendar"]){
    }else if([sourcename isEqualToString:@"note"]){
    }
    
}
    
// Thread that handles the animation of the rotating arrows, fired by a timer
// when Syncevolution ends (and syncGoing goes to FALSE) handles the visualization of the icons
// for a successful and failed sync, then stops the timer
- (void)syncContactsAnimation:(NSTimer *)timer
{
    
    if (contactButtonBlueFlag){
        [self.view addSubview:contactButtonBlue];
        [self.view addSubview:contactsText];
        [self.view addSubview:iconContacts];
        [self.view addSubview:contactsStatusText];
        contactButtonBlueFlag = false;
    }
    if(contactSyncAnimation){
        int idx = syncArrow % 4;
        [iconContactSyncDark[idx] removeFromSuperview];
        idx = ++syncArrow % 4;
        [self.view addSubview:iconContactSyncDark[idx]];
    }
    if (syncContactText != nil) {
        [contactsStatusText setText:syncContactText];
        [syncContactText release];
        syncContactText = nil;
    }
}

- (void)syncCalendarAnimation:(NSTimer *)timer
{
    if (calendarButtonBlueFlag){
        [self.view addSubview:calendarButtonBlue];
        [self.view addSubview:calendarText];
        [self.view addSubview:iconCalendar];
        [self.view addSubview:calendarStatusText];
        calendarButtonBlueFlag = false;
    }
    
    if(calendarSyncAnimation){
        int idx = syncArrow % 4;
        [iconCalendarSyncDark[idx] removeFromSuperview];
        idx = ++syncArrow % 4;
        [self.view addSubview:iconCalendarSyncDark[idx]];
    }
        
    if (syncCalendarText != nil) {
        [calendarStatusText setText:syncCalendarText];
        [syncCalendarText release];
        syncCalendarText = nil;
    }
}

- (void)syncNoteAnimation:(NSTimer *)timer
{
    if (noteButtonBlueFlag){
        [self.view addSubview:noteButtonBlue];
        
        [self.view addSubview:notesText];
        [self.view addSubview:iconNotes];
        [self.view addSubview:notesStatusText];
        noteButtonBlueFlag = false;
    }
    
    if(noteSyncAnimation){
        int idx = syncArrow % 4;
        [iconNoteSyncDark[idx] removeFromSuperview];
        idx = ++syncArrow % 4;
        [self.view addSubview:iconNoteSyncDark[idx]];
    }
        
    if (syncNoteText != nil) {
        [notesStatusText setText:syncNoteText];
        [syncNoteText release];
        syncNoteText = nil;
    }
}

- (void) startSyncArrowAnimation : (NSString*) sourcename {

    if([sourcename isEqualToString:@"addressbook"]){
        // Remove previous sync status icons
        [statusContactIcons[MAIN_VIEW_STATUS_ICON_SUCCESS] removeFromSuperview];
        [statusContactIcons[MAIN_VIEW_STATUS_ICON_FAILURE] removeFromSuperview];
        // Start the timer task
        timerContact = [NSTimer scheduledTimerWithTimeInterval:0.3
                                                 target:self selector:@selector(syncContactsAnimation:)
                                                 userInfo:nil repeats:YES];
    }else if([sourcename isEqualToString:@"calendar"]){
        // Remove previous sync status icons
        [statusCalendarIcons[MAIN_VIEW_STATUS_ICON_SUCCESS] removeFromSuperview];
        [statusCalendarIcons[MAIN_VIEW_STATUS_ICON_FAILURE] removeFromSuperview];
        // Start the timer task
        timerCalendar = [NSTimer scheduledTimerWithTimeInterval:0.3
                                                 target:self selector:@selector(syncCalendarAnimation:)
                                               userInfo:nil repeats:YES];
    }else if([sourcename isEqualToString:@"note"]){
        // Remove previous sync status icons
        [statusNoteIcons[MAIN_VIEW_STATUS_ICON_SUCCESS] removeFromSuperview];
        [statusNoteIcons[MAIN_VIEW_STATUS_ICON_FAILURE] removeFromSuperview];
        // Start the timer task
        timerNote = [NSTimer scheduledTimerWithTimeInterval:0.3
                                                 target:self selector:@selector(syncNoteAnimation:)
                                               userInfo:nil repeats:YES];
    }
}

- (void) cancelSyncArrowAnimation:(NSString*) sourcename{

    if([sourcename isEqualToString:@"addressbook"]){
        [timerContact invalidate];
        contactSyncAnimation = false;
        int idx = syncArrow % 4;
        [iconContactSyncDark[idx] removeFromSuperview];
    }else if([sourcename isEqualToString:@"calendar"]){
        [timerCalendar invalidate];
        calendarSyncAnimation = false;
        int idx = syncArrow % 4;
        [iconCalendarSyncDark[idx] removeFromSuperview];
    }else if([sourcename isEqualToString:@"note"]){
        [timerNote invalidate];
        noteSyncAnimation = false;
        int idx = syncArrow % 4;
        [iconNoteSyncDark[idx] removeFromSuperview];
    }

}

- (void)updateItemSyncStatus:(NSString*)msg sourcename:(NSString*) sourcename {
    
    [self updateItemSyncStatus: msg iconIdx:MAIN_VIEW_STATUS_ICON_NULL sourcename:sourcename];
}

- (void)updateItemSyncStatus:(NSString*)msg iconIdx:(StatusIconId) iconIdx sourcename:(NSString*) sourcename{

    if (msg != nil) {
        if([sourcename isEqualToString:@"addressbook"]){
            [contactsStatusText setText:msg];
            [self.view addSubview:contactsStatusText];
        }else if([sourcename isEqualToString:@"calendar"]){
            [calendarStatusText setText:msg];
            [self.view addSubview:calendarStatusText];
        }else if([sourcename isEqualToString:@"note"]){
            [notesStatusText setText:msg];
            [self.view addSubview:notesStatusText];
        }
    }
    if (iconIdx != MAIN_VIEW_STATUS_ICON_NULL) {
        if([sourcename isEqualToString:@"addressbook"]){
            [self.view addSubview:statusContactIcons[iconIdx]];

        }else if([sourcename isEqualToString:@"calendar"]){
            [self.view addSubview:statusCalendarIcons[iconIdx]];

        }else if([sourcename isEqualToString:@"note"]){
            [self.view addSubview:statusNoteIcons[iconIdx]];

        }
    }
}

// Sets the contact status string during a sync. Note that attempting to
// set status string via the updateContactSyncStatus during a sync does
// not work
- (void) updateItemsSyncStatusDuringSync:(NSString*)sourcename msg:(NSString*) msg{

    if([sourcename isEqualToString:@"addressbook"]){
        if (syncContactText)
        {
            [syncContactText release];
            syncContactText = nil;
        }
        syncContactText = msg;
    }else if([sourcename isEqualToString:@"calendar"]){
        if (syncCalendarText)
        {
            [syncCalendarText release];
            syncCalendarText = nil;
        }
        syncCalendarText = msg;
    }else if([sourcename isEqualToString:@"note"]){
        if (syncNoteText)
        {
            [syncNoteText release];
            syncNoteText = nil;
        }
        syncNoteText = msg;
    }
}

// Adds the icons displayed during a sync all
- (void)setSyncAllView {
    //[self addSubview:buttonDarkBlue];
    //[self addSubview:iconSyncAllBlue];
    //[self addSubview:iconLogo];
    //[self addSubview:allText];
	//[self setSyncContactsView];
	[self.view addSubview:buttonDarkBlue];
    [self.view addSubview:iconLogo];
	[self showStopButton];
}

// Adds the icons displayed during a sync all
- (void)setSyncSourceView:(NSString*)sourcename {

    //[self.view addSubview:iconSyncAllBlue];
    
    if([sourcename isEqualToString:@"addressbook"]){
        contactButtonBlueFlag = true;
    }else if([sourcename isEqualToString:@"calendar"]){
        calendarButtonBlueFlag = true;
    }else if([sourcename isEqualToString:@"note"]){
        noteButtonBlueFlag = true;
    }
    //[self addSubview:allText];
}

- (void) showStopButton{

	[allText removeFromSuperview];
    [self.view addSubview:synchronizeText];
    [self.view addSubview:syncCancelText];
}

- (void) removeButtonBlue: (NSString*) sourcename{
    if([sourcename isEqualToString:@"addressbook"]){
        [contactButtonBlue removeFromSuperview];
    }else if([sourcename isEqualToString:@"calendar"]){
        [calendarButtonBlue removeFromSuperview];
    }else if([sourcename isEqualToString:@"note"]){
        [noteButtonBlue removeFromSuperview];
    }
}
    

// This method removes all the icons that are set during sync
- (void)resetSyncIcons {
    //[contactButtonBlue removeFromSuperview];    
    [buttonDarkBlue removeFromSuperview];
    //[iconSyncAllBlue removeFromSuperview];
	[stopButton removeFromSuperview];
	[synchronizeText removeFromSuperview];
    [syncCancelText removeFromSuperview];
    [self.view addSubview:allText];

}

- (NSString*) getLastSyncMessage: (NSString*) source{
    int lastsync = [[FunambolAPI getInstance] getSyncSourceLastSyncDate:source];
    int today = time (NULL);
    
    NSDateComponents* todayDate = getDateComponentsFromDate1970(today);
    NSDateComponents* yesterdayDate = getDateComponentsFromDate1970((today - 86400));
    NSDateComponents* lastsyncDate = getDateComponentsFromDate1970(lastsync);
    
    if (lastsync == 0 ){
        return NSLocalizedString(@"Contacts never synched", @"Contacts never synched");
    }else if([todayDate year]   ==  [lastsyncDate year]     &&
             [todayDate month]  ==  [lastsyncDate month]    &&
             [todayDate day]    ==  [lastsyncDate day]){//today
        
        NSDate *lastSync = [NSDate dateWithTimeIntervalSince1970:lastsync];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
                
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        
        //NSString* lastSyncText = [lastSync descriptionWithCalendarFormat:NSLocalizedString(@"Dateformat",@"%A, %I:%M%p") timeZone:nil locale:nil];
        NSString* lastSyncText = [dateFormatter stringFromDate:lastSync];
        NSString* statusTextValue = NSLocalizedString(@"Last sync: ",@"Last sync: ");
            
        statusTextValue = [statusTextValue stringByAppendingString:NSLocalizedString(@"Today ",@"Today ")];
        lastSyncText = [statusTextValue stringByAppendingString:lastSyncText];
        return lastSyncText;
    }else if ([yesterdayDate year]   ==  [lastsyncDate year]     &&
              [yesterdayDate month]  ==  [lastsyncDate month]    &&
              [yesterdayDate day]    ==  [lastsyncDate day]){// yesterday
        NSDate *lastSync = [NSDate dateWithTimeIntervalSince1970:lastsync];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
        
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        
        //NSString* lastSyncText = [lastSync descriptionWithCalendarFormat:NSLocalizedString(@"Dateformat",@"%A, %I:%M%p") timeZone:nil locale:nil];
        NSString* lastSyncText = [dateFormatter stringFromDate:lastSync];
        
        NSString* statusTextValue = NSLocalizedString(@"Last sync: ",@"Last sync: ");
        statusTextValue = [statusTextValue stringByAppendingString:NSLocalizedString(@"Yesterday ",@"Yesterday ")];
        lastSyncText = [statusTextValue stringByAppendingString:lastSyncText];
        return lastSyncText;
    }else{
        
        NSDate *lastSync = [NSDate dateWithTimeIntervalSince1970:lastsync];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
        
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
        
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        
        //NSString* lastSyncText = [lastSync descriptionWithCalendarFormat:NSLocalizedString(@"Dateformat",@"%A, %I:%M%p") timeZone:nil locale:nil];
        NSString* lastSyncText = [dateFormatter stringFromDate:lastSync];
        
        NSString* statusTextValue = NSLocalizedString(@"Last sync: ",@"Last sync: ");
        lastSyncText = [statusTextValue stringByAppendingString:lastSyncText];
        return lastSyncText;
    }
    [yesterdayDate release];
    [todayDate release];
    [lastsyncDate release];    
}

- (void) showMessage: (NSString*) messageText titleText: (NSString*) titleText{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:titleText message:messageText
                                                   delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"OK") otherButtonTitles: nil];
    [alert show];
    [alert release];
    
    
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
     // the user clicked one of the OK/Cancel buttons
     if (buttonIndex == 0){
     }else{
         
     }
}

- (void) dealloc{
    [menuList release];
    
    [window release];
    [settingsButton release];
    [syncButton release];
	[contactsButton release];
	[stopButton release];
    [textView release];  
    [synchronizeText release];
    [syncCancelText release]; 
    [allText release];
    [contactsText release];
    [contactsStatusText release];
    [calendarText release];
    [calendarStatusText release];
    [tasksText release];
    [tasksStatusText release];
    [notesText release];
    [notesStatusText release];
    [textLabel release];
    [logo release];
    [background release];
    [buttonDarkBlue release];
    [contactButtonBlue release];
    [calendarButtonBlue release];
    [noteButtonBlue release];
    [iconSyncAllBlue release];
    [timerContact release];
    [timerCalendar release];
    [timerNote release];
    [syncContactText release];
    [syncCalendarText release];
    [syncNoteText release];

    [rightTitle release];
    
    
    [iconLogo release];
    [iconContacts release];
    [iconCalendar release];
    [iconTasks release];
    [iconNotes release];
	[navItem release];
    [large_font release];
    [small_font release];
    [super dealloc];
}
@end


